package com.comp490.input;

import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class TouchController implements OnTouchListener
{
    private float mInitialX, mInitialY;
    private float mPosX = 0, mPosY = 0;
    private int activePointer = -1;

    public boolean onTouch(View v, MotionEvent event)
    {
        // User Pressed on Screen
        if(MotionEvent.ACTION_DOWN == event.getActionMasked())
        {
        	activePointer = event.getPointerId(0);
			mInitialX = event.getX();
			mInitialY = event.getY();
            return true;
        }
        else if(MotionEvent.ACTION_POINTER_DOWN == event.getActionMasked())
        {
        	return true;
        }
        else if(MotionEvent.ACTION_POINTER_UP == event.getActionMasked())
        {
        	// Extract the index of the pointer that left the touch sensor
            final int pointerIndex = (event.getAction() & MotionEvent.ACTION_POINTER_INDEX_MASK) 
                    >> MotionEvent.ACTION_POINTER_INDEX_SHIFT;
            final int pointerId = event.getPointerId(pointerIndex);
            if(activePointer == pointerId)
            {
                // This was our active pointer going up. Choose a new
                // active pointer and adjust accordingly.
                final int newPointerIndex = pointerIndex == 0 ? 1 : 0;
                mInitialX = event.getX(newPointerIndex);
                mInitialY = event.getY(newPointerIndex);
                activePointer = event.getPointerId(newPointerIndex);
            }
			return true;
        }
        // User lifted finger from screen
        else if(MotionEvent.ACTION_UP == event.getActionMasked())	
        {
			mPosX = 0;
			mPosY = 0;
			activePointer = -1;
            return true;
        }
        // Move event happened between action_down and action_up
        else if(MotionEvent.ACTION_MOVE == event.getActionMasked())
        {
			// Find the index of the active pointer and fetch its position
			final int pointerIndex = event.findPointerIndex(activePointer);
			mPosX = event.getX(pointerIndex) - mInitialX;
			mPosY = event.getY(pointerIndex) - mInitialY;
			mInitialX = event.getX(pointerIndex);
			mInitialY = event.getY(pointerIndex);

			return true;
        }
        return false;
    }
    
    public float getmPosX()
    {
        // Hack was done to make sure mPosX continuously updates to
        // 0 in case player just places finger on screen and doesn't move
        float lastPosX = mPosX;
        mPosX = 0;
        return lastPosX;
    }

    public float getmPosY()
    {
        // Hack was done to make sure mPosX continuously updates to
        // 0 in case player just places finger on screen and doesn't move
        float lastPosY = mPosY;
        mPosY = 0;
        return lastPosY;
    }
}